{extend name='admin@public/content'}

{block name="content"}
<form onsubmit="return false;" action="{:request()->url()}" data-auto="true" method="post" id="ProductForm" class='form-horizontal layui-form padding-top-20'>

    {if !empty($cates)}
    <div class="form-group">
        <label class="col-sm-2 control-label">分类</label>
        <div class='col-sm-8 text-top'>
            <select required class="layui-select full-width" name="cate_id" lay-filter="cate_id">
                <option selected="" value="0">选择分类</option>
                {foreach $cates as $cate}
                <!--{if isset($vo.cate_id) and $cate.cate_id eq $vo.cate_id}-->
                <option selected value="{$cate.cate_id}">{$cate.name}</option>
                <!--{else}-->
                <option value="{$cate.cate_id}">{$cate.name}</option>
                <!--{/if}-->
                {/foreach}
            </select>
        </div>
    </div>
    {/if}



    <div class="form-group">
        <label class="col-sm-2 control-label">姓名</label>
        <div class='col-sm-8'>
            <input name="item" required value="{$vo.item|default=''}" class="layui-input" title="请输入姓名" placeholder="请输入姓名">
        </div>
    </div>



    <div class="form-group">
        <label class="col-sm-2 control-label">手机号</label>
        <div class='col-sm-8'>
            <input name="phone" required maxlength="11" value="{$vo.phone|default=''}" class="layui-input" title="请输入手机号" placeholder="请输入手机号">
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">学校</label>
        <div class='col-sm-8'>
            <input name="address" required value="{$vo.address|default=''}" class="layui-input" title="请输入学校" placeholder="请输入学校">
        </div>
    </div>




    <div class="hr-line-dashed"></div>

    <div class="col-sm-7 col-sm-offset-2">
        <div class="layui-form-item text-center">
            {if !empty($vo.id)}<input type="hidden" name="id" value="{$vo.id}">{/if}
            <button class="layui-btn" type="submit">提交</button>
            <button class="layui-btn layui-btn-danger" type='button' onclick="window.history.back()">取消</button>
        </div>
    </div>

</form>

<script>
    //腾讯云对象存储
    var cos = new COS({
        // 必选参数
        getAuthorization: function (options, callback) {
            $.ajax({
                method: 'GET',
                url: "{:url('admin/info/cos_sts')}",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Content-Type', 'application/json');
                },
                dataType: 'json',
                success: function (data) {
                    var credentials = data.data && data.data.credentials;
                    if (!data || !credentials) return console.error('credentials invalid');
                    callback({
                        TmpSecretId: credentials.tmpSecretId,
                        TmpSecretKey: credentials.tmpSecretKey,
                        XCosSecurityToken: credentials.sessionToken,
                        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                        StartTime: data.data.startTime, // 时间戳，单位秒，如：1580000000
                        ExpiredTime: data.data.expiredTime // 时间戳，单位秒，如：1580000900
                    });
                }
            });
        }
    });

    function getFileType(filePath) {

        //获取文件的后缀名
        var startIndex = filePath.lastIndexOf(".");
        if (startIndex != -1)
            return filePath.substring(startIndex + 1, filePath.length);
        else return "";
    }


    function checkImage(file) {
        const isLt1M = file.size / 1024 / 1024 < 50;
        console.log(file);
        var right_type = new Array("wmv", "mpg", "mpeg", "mov", "mp4");
        if (document.getElementById("file_upload").value != '') {
            type = document.getElementById("file_upload").value.match(/^(.*)(\.)(.{1,8})$/)[3];
//防止出问题，把获取到的所有结尾格式，全部转化为小写
            type = type.toLowerCase();
        }
        console.log(type);

        function isCon(arr, val) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == val)
                    return true;
            }
            return false;
        }

        var result = isCon(right_type, type);
        //可以打印开看结果，是布尔类型(Boolean)，也就是： true 或 false
        console.log(isCon(right_type, type));

        if (result == false) {
            alert('上传文件格式不支持，允许上传MP4和mov格式视频!')
            return false;
        }

        if (file.size > 0 && file.size > 1024 * 1024 * 50) {
            alert("上传文件大小不能超过 50MB");
            return false;
        }
        return true;
    }

    function getuuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
        var uuid = []
        var i = 0
        radix = radix || chars.length

        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
        } else {
            var r

            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
            uuid[14] = '4'

            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16
                    uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
                }
            }
        }

        return uuid.join('')
    }

    const domainUrl = "http://{:sysconf('storage_cos_domain')}/";

    $("#uploadcos").unbind('click').click(function () {
        $("#file_upload").click();
    });

    $(function () {
        $("#file_upload").change(function () {
            var $file = $(this);
            var fileObj = $file[0];
            var imgList = [];
            var windowURL = window.URL || window.webkitURL;
            var dataURL;
            var $img = $("#preview");
            //图片预览
            if (fileObj && fileObj.files && fileObj.files[0]) {
                dataURL = windowURL.createObjectURL(fileObj.files[0]);
                $img.attr('src', dataURL);
            } else {
                dataURL = $file.val();
                var imgObj = document.getElementById("preview");
                imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
            }
            // let fileObject = fileObj.files[0]
            let timestamp, imgTmp, key;
            for (i = 0; i < fileObj.files.length; i++) {

                type = document.getElementById("file_upload").value.match(/^(.*)(\.)(.{1,8})$/)[3];
                //防止出问题，把获取到的所有结尾格式，全部转化为小写
                type = type.toLowerCase();

                timestamp = 'static/xlj_video_2022/' + getuuid(30, 6) + '.' + type;
//                timestamp = 'static/xlj_video/openid/' + (new Date()).getTime() + '.' + type;
//                timestamp = 'static/xlj_video/openid/' + (new Date()).getTime();
                imgTmp = fileObj.files[i];
                if (checkImage(imgTmp)) {
                    var index = $.msg.loading('上传中...');
                    cos.putObject({
                        Bucket: "{:sysconf('storage_cos_bucket')}",
                        Region: "{:sysconf('storage_cos_endpoint')}",
                        Key: timestamp.toString(), /* 必须 */
                        StorageClass: 'STANDARD',
                        Body: imgTmp, // 上传文件对象
                        onProgress: function (progressData) {
//                            console.log(JSON.stringify(progressData));
                        }
                    }, function (err, data) {

                        $.msg.close(index);
                        if (data.statusCode == 200) {
                            $("#videourl").val(domainUrl + timestamp.toString());
                            $("#videoplay").prop("src",domainUrl + timestamp.toString())
//                            alert("上传成功的链接为：" + (domainUrl + timestamp.toString()))
                        } else {
                            alert("上传失败，请重试")
                        }
//                        console.log(err || data);
                        console.log(data);
                        console.log("上传成功的图片链接为：" + (domainUrl + timestamp.toString()))
                    });
                } else {
//                    alert("上传文件格式错误")
                }
            }
        });

    });

</script>


<script>
    require(['jquery', 'ckeditor', 'angular'], function () {
        window.form.render();
        window.createEditor('[name="intro"]', {height: 500});
        var app = angular.module("ProductForm", []).run(callback);
        angular.bootstrap(document.getElementById(app.name), [app.name]);

        function callback() {
            // 单图片上传处理
//            $('#ProductForm [name="small_pic"]').uploadOneImage();
            $('#ProductForm [name="startpicurl"]').uploadOneImage();
            $('#ProductForm [name="startpicurl2"]').uploadOneImage();
            $('#ProductForm [name="startpicurl3"]').uploadOneImage();
            $('#ProductForm [name="startpicurl4"]').uploadOneImage();
            $('#ProductForm [name="startpicurl5"]').uploadOneImage();
            $('#ProductForm [name="startpicurl6"]').uploadOneImage();
            $('#ProductForm [name="startpicurl7"]').uploadOneImage();
            $('#ProductForm [name="startpicurl8"]').uploadOneImage();
        }
    });
</script>
{/block}

{block name="style"}
<style>

    .background-item {
        padding: 15px;
        background: #efefef;
    }

    .background-item thead tr {
        background: #e0e0e0
    }

    .price-input-td {
        padding: 0 !important;
    }

    .price-input-td:before {
        margin: 4px;
        width: 35px;
        height: 22px;
        content: "金额";
        line-height: 20px;
        text-align: center;
        position: absolute;
        background: #e2e2e2;
    }

    .price-input-td input {
        height: 30px;
        padding-left: 50px;
        border: none !important;
    }
</style>
{/block}